import createElement from './create-element';
import mainExport from './main-export';
export default class ComponentRenderer {
  constructor(is, render) {
    this.is = is;
    this._render = render;
  }

  async get(Component = mainExport) {
    Component = await Component;

    if (!Component) {
      return;
    }

    if (this.is(Component)) {
      return Component;
    }

    Component = Component.default;

    if (this.is(Component)) {
      return Component;
    }
  }

  render(Component, props, htmlElement) {
    if (props instanceof HTMLElement) {
      [props, htmlElement] = [undefined, props];
    }

    if (!(htmlElement instanceof HTMLElement)) {
      htmlElement = createElement();
    }

    return this._render(Component, props || {}, htmlElement);
  }

  async renderDefault(props, htmlElement) {
    if (props instanceof HTMLElement) {
      [props, htmlElement] = [undefined, props];
    }

    if (!(htmlElement instanceof HTMLElement)) {
      htmlElement = createElement();
    }

    const Component = await this.get();

    if (!Component) {
      return;
    }

    return this.render(Component, props, htmlElement);
  }

}